package com.fangcun.controller.sys;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fangcun.bean.sys.ResponseMsg;
import com.fangcun.common.auth.UserAuthMethod;
import com.fangcun.common.canstant.ErrCode;
import com.fangcun.common.canstant.PublicConstant;
import com.fangcun.common.exception.ProException;
import com.fangcun.common.exception.ProValiDataException;
import com.fangcun.common.util.PublicMethod;
import com.fangcun.common.util.apiversion.ApiVersion;
import com.fangcun.common.util.date.DateUtils;
import com.fangcun.common.util.qiniu.QiniuUploadResponse;
import com.fangcun.common.util.qiniu.QiniuUtils;
import com.fangcun.service.SystemService;

/**
 * @作者： 陳曉鬆 @时间： 2020年4月28日 - 上午10:34:54 @description：-> 七牛云
 */
@RestController
@RequestMapping("/sys/{version}/qiniu")
public class QiniuController {

	private static Logger LOG = LoggerFactory.getLogger(QiniuController.class);

	@Autowired
	private QiniuUtils qiniuUtil;

	@Resource(name = "systemService")
	private SystemService systemService;

	/**
	 * 上传文件
	 * 
	 * @param type
	 *            1-上传商品图片 2-上传头像 3-动态图片上传
	 */
	@ApiVersion(1.0)
	@PostMapping("upload/image")
	public ResponseMsg uploadChatImage(@RequestParam("file") MultipartFile file, HttpServletRequest request, Integer type, String path) {
		ResponseMsg msg = ResponseMsg.returnBeanBuild();
		try {
			if (file.isEmpty()) {
				throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "没有获取到上传文件");
			}
			String fileName = getUploadPath(request, type, path) + "/" + DateUtils.DF_CLOSED.get().format(new Date()) + PublicMethod.getCode(10)
					+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			QiniuUploadResponse qinIuBean = qiniuUtil.upload(file.getBytes(), fileName);
			if (qinIuBean == null) {
				throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "文件上传失败文件");
			}
			return msg.setData(qinIuBean.getUrl() + qinIuBean.getKey());
		} catch (ProException e) {
			LOG.error("-七牛-上传图片出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
		} catch (Exception e) {
			LOG.error("-用户-上传图片异常->{},{}", msg.getSessionId(), PublicMethod.printErrorTrace(e));
			msg.setReturnCode(ErrCode.ERR.getReturnCode()).setReturnMsg(ErrCode.ERR.getReturnMsg());
		}
		return msg;
	}

	/**
	 * @作者：陳曉鬆 @时间：2020年6月12日 下午2:24:38 @版本：V1.0 @description：-> 得到上传路径
	 */
	private String getUploadPath(HttpServletRequest request, Integer type, String path) throws ProException {
		String token = request.getHeader(UserAuthMethod.LOGIN_TOKEN_NAME);
		if (type == null) {
			type = 1;
		}
		if (!StringUtils.isEmpty(path)) {
			path = String.valueOf(type) + "/" + path;
		} else {
			path = String.valueOf(type);
		}
		switch (type) {
		case 1:// 上传商品图片
			if (StringUtils.isEmpty(systemService.refreshLoginToken(token))) {// 需要登录
				throw new ProValiDataException(ErrCode.USER_LOGIN_BE_OVERDUE.getReturnCode(), ErrCode.USER_LOGIN_BE_OVERDUE.getReturnMsg());
			}
			path = PublicConstant.QINIU_CACHE_PATH + path;
			break;
		case 2:// 上传头像
			if (StringUtils.isEmpty(systemService.refreshLoginToken(token))) {// 需要登录
				throw new ProValiDataException(ErrCode.USER_LOGIN_BE_OVERDUE.getReturnCode(), ErrCode.USER_LOGIN_BE_OVERDUE.getReturnMsg());
			}
			path = path + "/" + UserAuthMethod.getLoginRedisKeyClass(token).getUserId();
			break;
		case 3:// 动态图片上传
			if (StringUtils.isEmpty(systemService.refreshLoginToken(token))) {// 需要登录
				throw new ProValiDataException(ErrCode.USER_LOGIN_BE_OVERDUE.getReturnCode(), ErrCode.USER_LOGIN_BE_OVERDUE.getReturnMsg());
			}
			path = PublicConstant.QINIU_CACHE_PATH + path + "/" + UserAuthMethod.getLoginRedisKeyClass(token).getUserId();
			break;
		}
		return path;
	}

	/**
	 * 
	 * @作者：陳曉鬆 @时间：2020年6月12日 下午2:38:07 @版本：V1.0 @description：-> 删除文件
	 */
	@ApiVersion(1.0)
	@PostMapping("delete")
	public ResponseMsg uploadChatImage(HttpServletRequest request, String url) {
		ResponseMsg msg = ResponseMsg.returnBeanBuild();
		try {
			if (StringUtils.isEmpty(url)) {
				throw new ProValiDataException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
			}
			String token = request.getHeader(UserAuthMethod.LOGIN_TOKEN_NAME);
			if (StringUtils.isEmpty(systemService.refreshLoginToken(token))) {// 需要登录
				throw new ProValiDataException(ErrCode.USER_LOGIN_BE_OVERDUE.getReturnCode(), ErrCode.USER_LOGIN_BE_OVERDUE.getReturnMsg());
			}
			msg.setData(qiniuUtil.deleteByPrefix(url));
		} catch (ProException e) {
			LOG.error("-七牛-删除出错->{},{},{}", msg.getSessionId(), e.getErrorCode(), e.getErrorMsg());
			msg.setReturnCode(e.getErrorCode()).setReturnMsg(e.getErrorMsg());
		} catch (Exception e) {
			LOG.error("-用户-删除异常->{},{}", msg.getSessionId(), PublicMethod.printErrorTrace(e));
			msg.setReturnCode(ErrCode.ERR.getReturnCode()).setReturnMsg(ErrCode.ERR.getReturnMsg());
		}
		return msg;
	}

}
